package com.bml.client.secret.demo.handler;

import cn.hutool.json.JSONObject;
import com.bml.client.secret.demo.jwt.JwtTokenUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

/**
 * @author: baiml
 * @Title: LoginResultHandler
 * @ProjectName: 中台技术平台
 * @Depart 中台研发部
 * @Description:
 * @date: 2021/6/29 16:26
 */
@Component
public class LoginResultHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler {

    private final String LOGIN_SUCCESS = "登录成功";

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    private final String FAILURE_INFO = "登录失败，用户名或者密码错误";

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String errorMsg = FAILURE_INFO;
        if (exception instanceof BadCredentialsException) {
            errorMsg = "密码错误";

        } else if (exception instanceof DisabledException) {
            errorMsg = "账户被禁用";
        } else if (exception instanceof AccountExpiredException) {
            errorMsg = "账户已过期";
        } else if (exception instanceof LockedException) {
            errorMsg = "账户已锁定";
        } else if (exception instanceof CredentialsExpiredException) {
            errorMsg = "账户凭证已过期";
        } else if (exception instanceof UsernameNotFoundException) {
            errorMsg = "账户不存在";
        }
        IOUtils.write(errorMsg, response.getOutputStream(), "utf-8");
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetails details = (UserDetails) authentication.getPrincipal();
        String s = jwtTokenUtil.generateToken(details);
        Collection<? extends GrantedAuthority> authorities = details.getAuthorities();
        StringBuilder builder = new StringBuilder();
        for (GrantedAuthority authority : authorities) {
            builder.append(authority.getAuthority()).append(",");
        }
        builder = builder.delete(builder.length()-1,builder.length());
        JSONObject json = new JSONObject();
        json.put("access_token",s);
        json.put("username",authentication.getName());
        json.put("roles",builder.toString());
        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(json.toString());
        out.flush();
        out.close();
    }
}
